from typing import Dict, List
from udsConsoleUi import Ui_udsConsole
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QColor
from PyQt5.QtWidgets import QWidget, QListView
from PyQt5 import QtGui
import os
from xml.dom.minidom import parse
import logging
from toolUds import ToolUds
import threading
import sys
LOG_NAME = 'udsConsole'

udsConsoleDict = {
    '0x10':ToolUds.udsDiagnosticSessionControl,
    '0x11':ToolUds.udsECUReset,
    '0x27':ToolUds.udsSecurityAccess,
    '0x22':ToolUds.udsReadDataByIdentifier,
}


class UdsConsole(QWidget,Ui_udsConsole):
    def __init__(self,parent) -> None:
        super(UdsConsole,self).__init__()
        self.udsConsoleForm = Ui_udsConsole()
        self.setupUi(self)
        self.parent = parent
        self.logger = logging.getLogger(LOG_NAME)

        self.itemModel = QStandardItemModel()
        self.itemModel.setHorizontalHeaderLabels(["service"])
        self.treeView.setModel(self.itemModel)
    
        
        self.loadInstanceConfig = self.loadUdsInstance()
        
        for udsInstance in self.loadInstanceConfig.keys():
            rootItem = QStandardItem(udsInstance)
            rootItem.setEditable(False)
            rootItem.setData(self.loadInstanceConfig[udsInstance]['SID'])
            for Instance in self.loadInstanceConfig[udsInstance]['ParamList'].keys():
                childrenNode =  QStandardItem(Instance)
                childrenNode.setEditable(False)
                childrenNode.setData(self.loadInstanceConfig[udsInstance]['ParamList'][Instance])
                rootItem.appendRow(childrenNode)

            self.itemModel.appendRow(rootItem)
        
        self.treeView.expandAll()
        
        self.treeView.doubleClicked.connect(self.treeViewDoubleClicked)
    
    def loadUdsInstance(self)-> dict:

        self.udsInstanceDict = {}
        domTree = parse('./XML/UDS-List.xml')
        rootNode = domTree.documentElement
        udsInstances = rootNode.getElementsByTagName('UdsDescription')

        for udsInstcance in udsInstances:
            udsDescription = udsInstcance.getAttribute('comments')
            udsSidValue = udsInstcance.getElementsByTagName('UdsSid')[0].childNodes[0].data
            udsParas = udsInstcance.getElementsByTagName('parameter')
            self.udsInstanceDict[udsDescription] = {
                'SID':udsSidValue,
                'ParamList':{}
            }
            for udsPara in udsParas:
                paraName =  udsPara.getAttribute('comments')
                paraValue =  udsPara.childNodes[0].data
                self.udsInstanceDict[udsDescription]['ParamList'].update({paraName:paraValue})
        self.logger.debug(self.udsInstanceDict)
        return self.udsInstanceDict
    
    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        self.close()
        return super().closeEvent(a0)
    
    def treeViewDoubleClicked(self,index):
        parentItemModel = self.itemModel.itemData(index.parent())
        childrenModel = self.itemModel.itemData(index)
        if parentItemModel:
            ServiceDescription = parentItemModel[0]
            ServiceSid = parentItemModel[257]
        else:
            ServiceDescription = None
            ServiceSid = None
            
        if childrenModel:
            ParameterDescription = childrenModel[0]
            Parameter = int(childrenModel[257],16)
        
        try:
            THT = threading.Thread(name=ServiceDescription,target=udsConsoleDict[ServiceSid](self=self.parent.testerTool ,session = Parameter))
            THT.start()
        except:
            self.logger.info(sys.exc_info()[1])
        else:
            pass
        
        
        
        
        




